from PIL import Image 
import requests
import cv2
import io
import numpy as np
import sys, getopt
import base64

# get os arges
opts, args = getopt.getopt(sys.argv[1:], "hd:p:o:H:")
deviceKey = ""
picId = ""
out = ""
os = False
apiHost = "http://172.16.20.60:9901"
for op, value in opts:
    if op == "-d":
        deviceKey = value
    elif op == "-p":
        picId = value
    elif op == "-o":
        out = value
    elif op == "-os":
        os = True 
    elif op == "-H":
        apiHost = value   
    elif op == "-h":
        print ('pic -d <deviceKey> -p <picId> -out [pic outputPath] ')
        sys.exit()

if deviceKey.strip() == "" or picId.strip() == "" : 
    print ('pic -d <deviceKey> -p <picId> -out [pic outputPath] ')
    sys.exit()
# get source img 
# imagepath = "https://static.leiphone.com/uploads/new/article/740_740/201704/5903040bf4146.jpg?imageMogr2/format/jpg/quality/90"
apiUrl = apiHost + "/devices/" + deviceKey + "/"+ picId
# payload = {'deviceKey': deviceKey , 'picId': picId ,'review': "7e8b84487bf545f68654623ad1572e45" }

res = requests.get(apiUrl,stream=True)
imgData = base64.b64decode(res.text)

imgData1 = np.asarray(bytearray(imgData), dtype="uint8")
image = cv2.imdecode(imgData1,cv2.IMREAD_COLOR)

# do img
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
face_cascade.load('/app/opencv/opencv-3.4.3/data/haarcascades/haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(
    gray,
    scaleFactor = 1.15,
    minNeighbors = 5,
    minSize = (5,5),
    flags = cv2.CASCADE_SCALE_IMAGE
)

for(x,y,w,h) in faces:
    cv2.rectangle(image,(x,y),(x+w,y+w),(0,255,0),2)
    # cv2.circle(image,((x+x+w)/2,(y+y+h)/2),w/2,(0,255,0),2)

# 
if out.strip() != "":
    print (out)
    cv2.imwrite(out,image)
   

# print ("find {0} face".format((faces)))